<?php

namespace app\api\controller;

use think\Request;
use app\api\model\GradeCharm;
use app\api\model\GradeNoble;
use app\api\model\GradeNobleTimes;
use app\api\model\GradeNoblePrivilege;

class Grade extends Common
{
    public function nobleList()
    {
        $data = GradeNoble::all(function($query){
            $query->order('sort desc');
        });

        $gradeNobleTimes = GradeNobleTimes::where(['id' => ['gt', 0]])->column('id, noble_id, name, price, keep, times, reward');
        $gradeNoblePrivilege = GradeNoblePrivilege::where(['is_hidden' => 0])->column('id, name, description, icon');

        foreach ($data as $key => $item) {
            $privilege = explode(',', $item['privilege']);
            $value = explode(',', $item['value']);

            $contain = [];
            foreach ($privilege as $v) {
                if (isset($gradeNoblePrivilege[$v])) {
                    $tempPrivilege = $gradeNoblePrivilege[$v];

                    $description = $tempPrivilege['description'];

                    foreach ($value as $m => $n) {
                        $description = str_replace('{'.$m.'}', $n, $description);
                    }
                    $tempPrivilege['description'] = $description;

                    $contain[] = $tempPrivilege;
                }
            }

            $times = [];
            foreach ($gradeNobleTimes as $v) {
                if ($item['id'] == $v['noble_id']) {
                    $times[] = $v;
                }
            }

            $data[$key]['privilege'] = $contain;
            $data[$key]['style'] = $times;

            unset($data[$key]['value']);
        }
        return $this->pass($data);
    }

    public function myGrade(Request $request = null)
    {
        $types = $request->param('types') ?: 1;

        $data = [];
        if ($types == 1) {
            $field = 'charm_value';

            $grade = GradeCharm::where(['min' => ['elt', $this->member[$field]]])->order('grade desc')->find();
            $nextGrade = GradeCharm::where(['min' => ['gt', $this->member[$field]]])->order('grade asc')->find();
        } else {
            $field = 'tycoon';

            $grade = GradeCharm::where(['min' => ['elt', $this->member[$field]]])->order('grade desc')->find();
            $nextGrade = GradeCharm::where(['min' => ['gt', $this->member[$field]]])->order('grade asc')->find();
        }

        $data['count'] = $this->member[$field];
        $data['grade'] = $grade->grade;
        $data['icon'] = $grade->icon;
        $data['upgrade'] = $nextGrade->min - $this->member[$field];

        return $this->pass($data);
    }
}
